/*
 * 客户地图
 * @author budao
 * @time 2020/07/18
 * @since 2.0.0
 * */
// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
// 引入antd的组件
import { message, Icon, Form, Modal, Row, Col, Spin, Button, Checkbox, Select, Radio, DatePicker } from 'antd'
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config'
// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
import { DateUtil } from 'utils/dateUtil'

// 当前组件样式
import styles from './customerMapStyle.less'
//引用listPage
import ListPage from 'widget/PageTmpl/ListPage'
import classnames from 'classnames/bind';
let cx = classnames.bind(styles);
import FlagBtn from 'widget/FlagBtn/FlagView'
// import { download } from "utils/util"
// import {Map, Marker, NavigationControl, InfoWindow} from 'react-bmap'
// import BMap from 'BMap'
import { AdvanceSearch } from 'widget/CollapsiblePanels/index'
import { QueryCondition } from 'widget/Grid/index'

import Bmap from 'widget/Bmap/Bmap';
import { func } from 'prop-types'
const confirm = Modal.confirm;

const CheckboxGroup = Checkbox.Group;
const Option = Select.Option
const RadioGroup = Radio.Group
const { RangePicker } = DatePicker




const ColStyle = {}
let $Child = null
/**
 * description 路由视图及事件处理
 * dispatch 分发到models中的effects对应事件名
 * model 用于获取models中state定义的数据
 * form 表单对象
 */
const RouteView = function ({ dispatch, model, form }) {
  // 表单的子函数
  const { resetFields, getFieldDecorator, validateFields, setFieldsValue } = form
  // 取出model对象，命名空间
  const { modelObj, namespace } = model

  const { hasData, search_city, customerTypearr,
    showcustomerBody,
    map_province,
    map_city,
    map_district,
    bamapsff,
    productIdList1,
    isReset,
    productIdList,
    locationType,
    startDate,
    endDate, customerList, allMIS, not_visitList, visitedList, dealList,
    not_visitNum, visitedNum, dealNum, allNum, customerLine, searchWeek, customerTypeList, getZoom, map_level, loading, queryList, center, markers, provinceData, province, sourceList, dateType } = modelObj

  const ColStyle = {
    xs: { span: 24 },
    md: { span: 24 },
    lg: { span: 12 },
    xl: { span: 6 }
  }

  function getProvince(e) {
    let params = {
      map_level: e.map_level,
      customerTypeList: customerTypeList,
      startDate,
      endDate,
      locationType,
      search_city: e.search_city,
      productIdList
    }
    dispatch({ type: `${namespace}/search`, payload: params })

    dispatch({
      type: `${namespace}/updateStore`, payload: {
        getZoom: e.getZoom,
        map_level: e.map_level,
        customerTypeList: customerTypeList,
        startDate,
        endDate,
      }
    })
  }
  // 切换客户类型
  function onChange(e, index, label) {
    let checked = e.target.checked
    if (checked) {
      if (index == 0) {
        customerTypeList.push('not_visit')
      } else if (index == 1) {
        customerTypeList.push('visited')
      } else if (index == 2) {
        customerTypeList.push('deal')
      }
    } else {
      if (customerTypeList.length == 1) {
        message.warning('至少选一个客户类型');
        return false
      }
      let idx = customerTypeList.indexOf(label)
      customerTypeList.splice(idx, 1)
    }
    for (let i = 0; i < sourceList.length; i++) {
      sourceList[index].checked = checked
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {
        customerTypeList,
        sourceList
      }
    })
  }

  function selectDate(e) {
    let type = e.target.value
    let startDate1 = ""
    let endDate1 = ""

    switch (type) {
      case 1:
        startDate1 = DateUtil.getStartDayOfWeek()
        endDate1 = DateUtil.getEndDayOfWeek()
        break;
      case 2:
        startDate1 = DateUtil.getStartDayOfMonth()
        endDate1 = DateUtil.getEndDayOfMonth()
        break;
      case 3:
        startDate1 = DateUtil.getQuarterStartDate()
        endDate1 = DateUtil.getQuarterEndDate()
        break;
      case 4:
        let startStop = DateUtil.getCurrentYear()
        startDate1 = startStop[0]
        endDate1 = startStop[1]
        break;
      default:
        break;
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {
        dateType: type,
        startDate: startDate1,
        endDate: endDate1,
        searchWeek: type
      }
    })
  }

  // 自定义时间
  function changeDate(dates, dateStrings) {
    let startDates = dateStrings[0]
    let endDates = dateStrings[1]
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {
        startDate: startDates,
        endDate: endDates
      }
    })
  }
  // 切换客户地图数据头部列表
  function changVis(item) {
    let arr = [], customerTypearr = []
    if (item == 'all') {
      arr = allMIS
      customerTypearr = 'all'
    } else if (item == 'notVisit') {
      arr = not_visitList
      customerTypearr = 'not_visit'
    } else if (item == 'hasVisited') {
      arr = visitedList
      customerTypearr = 'visited'
    } else if (item == 'traded') {
      arr = dealList
      customerTypearr = 'deal'
    }
    $Child.setcustomerType(customerTypearr)
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {
        customerLine: item,
        customerList: arr,
        customerTypearr
      }
    })
  }
  // 获取客户地图数据
  function getCustomerList(e) {
    let list = []
    switch (customerLine) {
      case 'all':
        list = e.allMIS
        break;
      case 'notVisit':
        list = e.not_visitList
        break;
      case 'hasVisited':
        list = e.visitedList
        break;
      case 'traded':
        list = e.dealList
        break;
      default:
        list = e.allMIS
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {
        ...e,
        customerList: list,
      }
    })
  }
  function clearSEclect(params) {
    dispatch({
      type: `${namespace}/queryReset`,
      payload: { reset: params }
    })
  }
  function changBampa() {
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {
        bamapsff: 0
      }
    })
  }
  function searchDa() {
    if (search_city == '' && productIdList.length == 0) {
      message.error('搜索失败！请选择区域-城市-项目后查询');
      return false
    } else if (search_city == '') {
      message.error('搜索失败！请选择城市');
      return false
    } else if (productIdList.length == 0) {
      message.error('搜索失败！请选择项目');
      return false
    }

    let goo = getZoom, zmap_level = map_level
    // 调用子组件方法,缩放地图
    // $Child.zoomInAndZoomOut(goo, search_city)
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {
        getZoom: goo,
        copygetZoom: goo,
        search_city,
        map_level: zmap_level,
        productIdList1: productIdList,
        bamapsff: 1,
        isReset: false,
        customerTypearr: 'all', // 重置客户地图数据切换过滤
        customerLine: 'all'
      }
    })
    $Child.setcustomerType('all')
    dispatch({
      type: `${namespace}/search`,
      payload: {
        map_level: zmap_level,
        search_city,
        productIdList,
        locationType,
        startDate,
        endDate,
        customerTypeList,
      }
    })
  }
  function chongzhi() {
    let startDate1 = DateUtil.getStartDayOfWeek()
    let endDate1 = DateUtil.getEndDayOfWeek()
    dispatch({
      type: `${namespace}/search`,
      payload: {
        startDate: startDate1,
        endDate: endDate1,
        map_level: 1,
        customerTypeList: ['not_visit'],
        locationType: 'all'
      }
    })
    // 调用子组件方法,缩放地图
    $Child.zoomInAndZoomOut(5, search_city)
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {
        isReset: true
      }
    })
    dispatch({ type: `${namespace}/queryReset`, payload: { reset: false } })
  }
  function handleCustomerBody() {
    let isshow = !showcustomerBody
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {
        showcustomerBody: isshow
      }
    })
  }
  const spinSTyle = {
    width: "100%", height: "calc(100vh - 255px)",
    backgroundColor: 'rgba(0,0,0,0.5)',
    position: 'absolute',
    top: 0, left: 0,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    zIndex: 999
  }
  return (
    <div>
      <div className={cx('pageLayout')}>
        <AdvanceSearch
          footer={
            <span>
              <Button type="primary" htmlType="submit" onClick={() => searchDa()} loading={loading}>搜索</Button>
              <Button onClick={() => chongzhi()}>重置</Button>
            </span>
          }
        >
          <QueryCondition
            data={queryList}
            inputChange={(key, value) => {
              dispatch({ type: `${namespace}/inputChange`, payload: { key, value } })
            }}
            ColStyle={ColStyle}
          />

        </AdvanceSearch>
        <Row className={cx('searchRow')}>
          <Col span={12}>
            <span>客户类型：</span>
            {
              sourceList.map((item, index) => {
                return (
                  <Checkbox checked={item.checked} onChange={(e) => { onChange(e, index, item.value) }}>
                    <img className={cx('selectimg')} src={item.img} alt="" />
                    {item.label}
                  </Checkbox>
                )
              })
            }
          </Col>
          <Col span={2}><span>统计日期：</span></Col>
          <Col span={10}>
            <RadioGroup value={searchWeek} onChange={(e) => { selectDate(e) }}>
              <Radio value={1}>
                本周
                </Radio>
              <Radio value={2}>
                本月
                </Radio>
              <Radio value={3}>
                本季度
                </Radio>
              <Radio value={4}>
                本年
                </Radio>
              <Radio value={5}>
                自定义
                  {dateType === 5 ? <RangePicker onChange={(dates, dateStrings) => { changeDate(dates, dateStrings) }} /> : null}
              </Radio>
            </RadioGroup>
          </Col>
        </Row>

        <div className={cx('customermapCont')}>
          {
            hasData && <div style={{ ...spinSTyle }}>
              <Spin tip="加载中..."></Spin>
            </div>
          }
          <div className={cx('customerBody')}>
            <div className={cx('customerTitle')} onClick={() => handleCustomerBody()}>
              <div>客户地图数据</div>
              {showcustomerBody && <img src="https://zmzj-pro.oss-cn-shenzhen.aliyuncs.com/pc/icon_open_a%402x.png" alt="" srcset="" />}
              {!showcustomerBody && <img src="https://zmzj-pro.oss-cn-shenzhen.aliyuncs.com/pc/icon_open_b%402x.png" alt="" srcset="" />}
            </div>
            {showcustomerBody && <div className={cx('customerBar')}>
              <div onClick={() => changVis('all')} className={[cx('lineBottom'), customerLine == 'all' ? cx('baseline') : null].join(' ')}>
                <div>全部</div>
                <div className={[customerLine == 'all' ? cx('seleco') : cx('fontss')].join(' ')}>{allNum}</div>
              </div>
              <div onClick={() => changVis('notVisit')} className={[cx('lineBottom'), customerLine == 'notVisit' ? cx('baseline') : null].join(' ')}>
                <div>未到访</div>
                <div className={[customerLine == 'notVisit' ? cx('seleco') : cx('fontss')].join(' ')}>{not_visitNum}</div>
              </div>
              <div onClick={() => changVis('hasVisited')} className={[cx('lineBottom'), customerLine == 'hasVisited' ? cx('baseline') : null].join(' ')}>
                <div>已到访</div>
                <div className={[customerLine == 'hasVisited' ? cx('seleco') : cx('fontss')].join(' ')}>{visitedNum}</div>
              </div>
              <div onClick={() => changVis('traded')} className={[cx('lineBottom'), customerLine == 'traded' ? cx('baseline') : null].join(' ')}>
                <div>已成交</div>
                <div className={[customerLine == 'traded' ? cx('seleco') : cx('fontss')].join(' ')}>{dealNum}</div>
              </div>
            </div>}
            {showcustomerBody && <div>
              {customerList && customerList.length > 0 ?
                <ul className={cx('customerList')} style={{ height: 'calc(100vh - 400px)' }}>
                  {customerList.map((item, index) => {
                    return (
                      <li key={index} className={cx('listItem')}>
                        <div>{map_level == 1 ? item.province : map_level == 2 ? item.city : item.district}</div>
                        <div>{item.count}</div>
                      </li>
                    )
                  })}
                </ul>
                :
                <div className={cx('nodata')} style={{ height: 'calc(100vh - 400px)' }}>
                  <img src="https://zmzj-pro.oss-cn-shenzhen.aliyuncs.com/pc/icon_no_data%402x.png" alt="" srcset="" />
                  <div>暂无数据</div>
                </div>
              }
            </div>}
          </div>
          <Bmap
            id="Bmap-a"
            customerTypearr={customerTypearr}
            bamapsff={bamapsff}
            value={center}
            getZoom={getZoom}
            map_level={map_level}
            center={center}
            markers={markers}
            search_city={search_city}
            province={map_province}
            provinceData={provinceData}
            productIdList={productIdList1}
            clearSEclect={(e) => clearSEclect(e)}
            changBampa={() => changBampa()}
            getCustomerList={(e) => getCustomerList(e)}
            onRef={(ref) => { $Child = ref }}
            getProvince={(e) => getProvince(e)} />
        </div>

      </div>
    </div>

  )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(RouteView))